<?php
// app/Controller/UsersController.php
class UsersController extends AppController {
    
    var $uses = array(
       'User','Package','PackagesModule','Bdc','BdcUser','Omc','OmcUser'
    );

    # Set the layout to use

    
    public function beforeFilter() {
        parent::beforeFilter();
        $this->Auth->allow('login','logout','add','signup','signup_company','signup_administrator',
            'signup_pricing_plans','signup_review','do_signup','signup_complete',
            'signup_cancel'
        );
    }
	
	public function login($id=null) {
	    if ($this->request->is('post')) {
	        //$this->autoRender = false;
	        //$this->autoLayout = false;
            $success = true;
            
            if ($this->Auth->login()) {
                /** Check if account is disabled*/
                $active = $this->Auth->user('active');
                $user_type = $this->Auth->user('user_type');
                $user_id = $this->Auth->user('id');

                $user_level = $this->Auth->user('user_level');
                if($active == 'n'){ /** User is disable, Logout */
                    $success = false;
                    $this->Auth->logout();
                    $this->Session->setFlash(__('Your Account is Disabled.'));
                }
                if($success){
                    $cp = null;
                    if($user_type == 'bdc'){
                        $us = $this->BdcUser->getUserById($user_id, -1);
                        $company_profile = $this->Bdc->getBdcById($us['BdcUser']['bdc_id']);
                        $cp = $company_profile['Bdc'];
                    }
                    elseif($user_type == 'omc'){
                        $us = $this->OmcUser->getUserById($user_id, -1);
                        $company_profile = $this->Omc->getOmcById($us['OmcUser']['omc_id']);
                        $cp = $company_profile['Omc'];
                    }

                    $this->Session->write('CompanyProfile',$cp);
                }
    		} 
            else {
                $success = false;
                $this->Session->setFlash(__('Invalid login Credentials'));
    		}

            if($success){//Login Successful
                $this->redirect(array('controller'=>'Dashboard','action'=>'index'));
            }
        }

        $this->set(compact('title_for_layout','company_profile'));

	}

	public function logout() {
       $this->Session->destroy();
	   $this->redirect($this->Auth->logout());
	}


    public function signup_company(){
        if ($this->request->is('post')) {
            if($this->Session->check('signup')){
                $signup = $this->Session->read('signup');
                $signup['Company']= $this->request->data;
                $this->Session->write('signup',$signup);
            }
            else{
                $signup['Company']= $this->request->data;
                $this->Session->write('signup',$signup);
            }
            $this->Session->write('step1_done','complete');
            $this->redirect('signup_administrator');
        }
        $this->layout = 'signup_layout';
        $title_for_layout = 'Company Info';
        $this->set(compact('title_for_layout'));
    }

    public function signup_administrator(){
        if(!$this->Session->check('step1_done')){
            $this->redirect('signup_company');
        }

        if ($this->request->is('post')) {
            if($this->Session->check('signup')){
                $signup = $this->Session->read('signup');
                $signup['User']= $this->request->data;
                $this->Session->write('signup',$signup);
            }
            else{
                $signup['User']= $this->request->data;
                $this->Session->write('signup',$signup);
            }
            $this->Session->write('step2_done','complete');
            $this->redirect('signup_pricing_plans');
        }

        $controller = $this;
        $this->layout = 'signup_layout';
        $title_for_layout = 'Create Admin Account';
        $this->set(compact('title_for_layout','controller'));
    }

    public function signup_pricing_plans(){
        if(!$this->Session->check('step2_done')){
            $this->redirect('signup_administrator');
        }

        if ($this->request->is('post')) {
            if($this->Session->check('signup')){
                $signup = $this->Session->read('signup');
                $signup['Modules']= $this->request->data;
                $this->Session->write('signup',$signup);
            }
            else{
                $signup['Modules']= $this->request->data;
                $this->Session->write('signup',$signup);
            }
            $this->Session->write('step3_done','complete');
            $this->redirect('signup_review');
        }

        $packages = $this->Package->find('all',array(
            'conditions'=>array('Package.deleted'=>'n'),
            'recursive'=>-1
        ));

        $this->layout = 'signup_layout';
        $title_for_layout = 'Select Packages';
        $this->set(compact('title_for_layout','packages'));
    }

    public function signup_review(){
        if(!$this->Session->check('step3_done')){
            $this->redirect('signup_pricing_plans');
        }

        $ids = array();
        $signup = $this->Session->read('signup');
        $modules = $signup['Modules'];
        foreach($modules as $key => $value){
            if(intval($value) > 0){
                $ids[]= $value;
            }
        }
        $packages = $this->Package->find('all',array(
            'conditions'=>array('Package.id'=>$ids,'Package.deleted'=>'n'),
            'recursive'=>-1
        ));
        $controller = $this;
        $this->layout = 'signup_layout';
        $title_for_layout = 'Review';
        $this->set(compact('title_for_layout','packages','controller'));
    }

    public function do_signup(){
        $this->autoRender = false;
        $this->autoLayout = false;
        $signup = $this->Session->read('signup');
        //Save the admin account data
        $user = array();
        $user['User']=$signup['User'];
        //Check if username exist
        $user_exist = $this->User->find('first',array(
            'conditions'=>array('User.username'=>$user['User']['username']),
            'recursive'=>-1
        ));

        if($user_exist){
            $this->Session->write('flash_msg',array('msg'=>'The username already exist.'));
            $this->redirect('signup_administrator');
        }

        //Get the module_id's for the selected package
        $package_id = $signup['Modules']['package_id'];
        $modules = $this->PackagesModule->find('all',array(
            'conditions'=>array('PackagesModule.package_id'=>$package_id),
            'recursive' => -1
        ));

        if($this->User->save($user)){
            $user_id = $this->User->id;
            //save the company data
            $company = array();
            $company['Bdc']=$signup['Company'];
            $company['BdcUser'][0]=array(
                'user_id'=> $user_id
            );
            $this->Bdc->saveAll($company);
            $company_id = $this->Bdc->id;
            $company_modules = array();
            $count = 0;
            foreach($modules as $value){
                $mod_id = $value['PackagesModule']['module_id'];
                $company_modules['BdcModule'][$count]=array(
                    'bdc_id'=>$company_id,
                    'module_id' => $mod_id
                );
                $count++;
            }
            $this->Bdc->BdcModule->saveAll($company_modules['BdcModule']);

            $this->redirect("signup_complete/".$this->Bdc->id);
        }
        else{
            $this->Session->write('flash_msg',array('msg'=>'Data save error, please try again'));
            $this->redirect('signup_review');
        }
    }

    public function signup_complete($id){
        $this->Session->destroy();
        $this->layout = 'signup_layout';
        $title_for_layout = 'Registration Complete';
        $this->set(compact('title_for_layout','id'));
    }


    public function signup_cancel(){
        $this->Session->destroy();
        $this->redirect(array('controller'=>'pages', 'action' => 'display', 'home'));
    }

    /**
     * This function is for making some changes to the user profile
     * @name profile
     * @param void
     * @return void
     * @access public
     */
    public function profile(){
        $this->layout = 'default';
        $page_title = 'Profile';
        $this->set(compact('page_title'));
    }
    
    /**
	 * This function redirects the user to his appropriate page after login
	 * @name signIn
	 * @param void
	 * @return void
	 * @access public
	 */
	function action_after_login(){
		$this->redirect(array('controller' => 'Dashboard', 'action' => 'index'));
	}
    
    
	
	public function add() {
        if ($this->request->is('post')) {
            echo debug($this->request->data);
            $this->User->create();
            if ($this->User->save($this->request->data)) {
                echo 'The user has been saved';
                $this->redirect(array('action' => 'index'));
            } else {
                echo 'The user could not be saved. Please, try again.';
            }
        }
    }

}